﻿import game.GUI;
import game.Main;
import game.Match;
import game.WordDefinition;
import mx.data.encoders.Num;
import mx.utils.Delegate;
/**
* ...
* @author Default
*/

class game.Session {
	private var _xml:XML;
	
	
	public var _cCurrentMatch:Match;
	public var _aDefinitions:Array;
	public var _nRound:Number = 0;
	
	private static var _cInstance:Session = null;
	
	public static function getInstance():Session{  // Singleton
		if ( !Session._cInstance )	{
			_cInstance = new Session();
		}
		
		return Session._cInstance;
	}
	
	public function Session() {
		
	}
	
	public function initialize():Void {
		LoadLevelsFromXML();
	
	}
	
	public function loadNewMatch(index:Number):Void {
		
		Main.getInstance()._cGUI.setRound(_nRound);
		_cCurrentMatch = new Match( _aDefinitions[index] );
		_aDefinitions.splice(index, 1); // Delete from the definition the current match
	}
	
	private function LoadLevelsFromXML() {
		_xml 				= new XML();
		_xml.ignoreWhite 	= true;
		_xml.onLoad 		= Delegate.create(this, fileLoaded);
		_xml.load("splitwords_puzzle.xml");
	}
	
	private function fileLoaded(loaded:Boolean){
		if (!loaded) { trace("ERROR LOADING THE XML"); return; }
		
		_aDefinitions = new Array();
		
		var _puzzles:XMLNode		= _xml.firstChild;
			
		var definition:WordDefinition;
		var _word:XMLNode;
		
		for ( var i:Number = 0 ; i< _puzzles.childNodes.length ; i++ ) {
			_word 		= _puzzles.childNodes[i];
			definition	= new WordDefinition(_word.attributes["Theme"], _word.attributes["Word1"], _word.attributes["Word2"], _word.attributes["image"] );
			_aDefinitions.push(definition);
		}
		
		definitionsLoaded();
	}
	
	public function nextMatch():Void {
		_nRound++;
		loadNewMatch( (Math.random() * _aDefinitions.length)>>0 )
	}
	
	public function firstMatch():Void {
		Main.getInstance()._cSoundManager.game1Start();
		nextMatch();
		GUI.getInstance()._cTimer.start( Number( Main.getInstance()._cAppConfigFile.getData ( "roundTime") ) );
		GUI.getInstance()._cTimer.startMainTimer(180);
	}
	
	private function definitionsLoaded():Void {
	
		//	loadNewMatch( (Math.random() * _aDefinitions.length)>>0 )
	}
	

	
}